package com.hl.qzzpbackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hl.qzzpbackend.common.DeleteRequest;
import com.hl.qzzpbackend.exception.BusinessException;
import com.hl.qzzpbackend.exception.ErrorCode;
import com.hl.qzzpbackend.exception.ThrowUtils;
import com.hl.qzzpbackend.model.dto.job.JobAddRequest;
import com.hl.qzzpbackend.model.dto.job.JobCheckRequest;
import com.hl.qzzpbackend.model.dto.job.JobQueryRequest;
import com.hl.qzzpbackend.model.dto.job.JobUpdateRequest;
import com.hl.qzzpbackend.model.entity.CompanyInfo;
import com.hl.qzzpbackend.model.entity.Job;
import com.hl.qzzpbackend.model.entity.PositionType;
import com.hl.qzzpbackend.model.enums.*;
import com.hl.qzzpbackend.model.vo.JobVO;
import com.hl.qzzpbackend.service.CompanyInfoService;
import com.hl.qzzpbackend.service.JobService;
import com.hl.qzzpbackend.mapper.JobMapper;
import com.hl.qzzpbackend.service.PositionTypeService;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 职位信息 业务层
 *
 * @author helong
*/
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job>
    implements JobService{

    @Resource
    private CompanyInfoService companyInfoService;

    @Resource
    private PositionTypeService positionTypeService;

    @Resource
    private JobMapper jobMapper;


    /**
     * 新增职位
     * @param jobAddRequest 新增职位请求类
     * @return 是否成功
     */
    @Override
    public boolean jobAdd(JobAddRequest jobAddRequest) {
        Long companyId = jobAddRequest.getCompanyId();
        Long positionTypeId = jobAddRequest.getPositionTypeId();
        Integer huntingType = jobAddRequest.getHuntingType();
        Integer education = jobAddRequest.getEducation();
        Integer experience = jobAddRequest.getExperience();
        List<String> tags = jobAddRequest.getTags();
        Integer minSalary = jobAddRequest.getMinSalary();
        Integer maxSalary = jobAddRequest.getMaxSalary();
        Integer checkStatus = jobAddRequest.getCheckStatus();
        Date pubTime = jobAddRequest.getPubTime();
        Date endTime = jobAddRequest.getEndTime();
        Integer jobState = jobAddRequest.getJobState();
        HuntingTypeEnum huntingTypeEnum = HuntingTypeEnum.getEnumByValue(huntingType);
        EducationEnum educationEnum = EducationEnum.getEnumByValue(education);
        ExperienceEnum experienceEnum = ExperienceEnum.getEnumByValue(experience);
        JobStateEnum jobStateEnum = JobStateEnum.getEnumByValue(jobState);
        CheckStatusEnum checkStatusEnum = CheckStatusEnum.getEnumByValue(checkStatus);

        // 参数校验
        validate(huntingTypeEnum, educationEnum, experienceEnum, jobStateEnum, checkStatusEnum, minSalary, maxSalary, pubTime, endTime, companyId, positionTypeId);

        Job job = new Job();
        BeanUtil.copyProperties(jobAddRequest, job);
        String tagsStr = JSONUtil.toJsonStr(tags);
        job.setTags(tagsStr);

        boolean result = this.save(job);
        if(!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加职位失败");
        }
        return true;
    }

    /**
     * 更新职位信息
     * @param jobUpdateRequest 更新职位信息请求类
     * @return 是否成功
     */
    @Override
    public boolean jobUpdate(JobUpdateRequest jobUpdateRequest) {
        Long id = jobUpdateRequest.getId();
        Long companyId = jobUpdateRequest.getCompanyId();
        Long positionTypeId = jobUpdateRequest.getPositionTypeId();
        Integer huntingType = jobUpdateRequest.getHuntingType();
        Integer education = jobUpdateRequest.getEducation();
        Integer experience = jobUpdateRequest.getExperience();
        List<String> tags = jobUpdateRequest.getTags();
        Integer minSalary = jobUpdateRequest.getMinSalary();
        Integer maxSalary = jobUpdateRequest.getMaxSalary();
        Integer checkStatus = jobUpdateRequest.getCheckStatus();
        Date pubTime = jobUpdateRequest.getPubTime();
        Date endTime = jobUpdateRequest.getEndTime();
        Integer jobState = jobUpdateRequest.getJobState();
        HuntingTypeEnum huntingTypeEnum = HuntingTypeEnum.getEnumByValue(huntingType);
        EducationEnum educationEnum = EducationEnum.getEnumByValue(education);
        ExperienceEnum experienceEnum = ExperienceEnum.getEnumByValue(experience);
        JobStateEnum jobStateEnum = JobStateEnum.getEnumByValue(jobState);
        CheckStatusEnum checkStatusEnum = CheckStatusEnum.getEnumByValue(checkStatus);


        validate(huntingTypeEnum, educationEnum, experienceEnum, jobStateEnum, checkStatusEnum, minSalary, maxSalary, pubTime, endTime, companyId, positionTypeId);
        long count = this.lambdaQuery().eq(Job::getId,id).count();
        ThrowUtils.throwIf(count == 0, ErrorCode.NOT_FOUND_ERROR, "职位不存在");

        Job job = new Job();
        BeanUtil.copyProperties(jobUpdateRequest, job);
        String tagsStr = JSONUtil.toJsonStr(tags);
        job.setTags(tagsStr);

        boolean result = this.updateById(job);
        if(!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新职位失败");
        }
        return true;
    }


    /**
     * 删除职位信息
     * @param deleteRequest 删除请求类
     * @return 是否成功
     */
    @Override
    public boolean jobDelete(DeleteRequest deleteRequest) {
        Long id = deleteRequest.getId();

        // 参数校验
        Job oldJob = this.getById(id);
        ThrowUtils.throwIf(oldJob == null, ErrorCode.NOT_FOUND_ERROR, "职位不存在");
        ThrowUtils.throwIf(JobStateEnum.PUB.getValue().equals(oldJob.getJobState()), ErrorCode.PARAMS_ERROR, "职位已发布，无法删除");

        boolean result = this.removeById(id);
        if(!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除职位失败");
        }
        return true;
    }


    /**
     * 获取职位详情
     * @param jobId 职位id
     * @return 职位详情
     */
    @Override
    public JobVO jobDetail(Long jobId) {
        // 参数校验
        ThrowUtils.throwIf(jobId == null, ErrorCode.PARAMS_ERROR, "职位id不能为空");
        Job oldJob = this.getById(jobId);
        ThrowUtils.throwIf(oldJob == null, ErrorCode.NOT_FOUND_ERROR, "职位不存在");

        JobVO jobVO = new JobVO();
        BeanUtil.copyProperties(oldJob, jobVO);
        List<String> tags = JSONUtil.toList(oldJob.getTags(), String.class);
        jobVO.setTags(tags);

        return jobVO;
    }


    /**
     * 分页查询职位信息 (根据条件)
     * @param jobQueryRequest 职位查询请求类
     * @return 职位信息分页结果
     */
    @Override
    public Page<JobVO> jobPageByCondition(JobQueryRequest jobQueryRequest) {
        int current = jobQueryRequest.getCurrent();
        int pageSize = jobQueryRequest.getPageSize();

        Page<JobVO> page = new Page<>(current, pageSize);
        jobMapper.jobPageByCondition(page,jobQueryRequest);

        return page;
    }

    /**
     * 审核职位
     * @param jobCheckRequest 审核请求类
     * @return 是否成功
     */
    @Override
    public boolean jobCheck(JobCheckRequest jobCheckRequest) {
        Long id = jobCheckRequest.getId();
        Integer checkStatus = jobCheckRequest.getCheckStatus();
        CheckStatusEnum checkStatusEnum = CheckStatusEnum.getEnumByValue(checkStatus);

        // 参数校验
        ThrowUtils.throwIf(checkStatusEnum == null, ErrorCode.PARAMS_ERROR, "审核状态错误");
        Job oldJob = this.getById(id);
        ThrowUtils.throwIf(oldJob == null, ErrorCode.NOT_FOUND_ERROR, "职位不存在");
        ThrowUtils.throwIf(checkStatus.equals(oldJob.getCheckStatus()), ErrorCode.PARAMS_ERROR, "职位不能重复审核");

        Job job = new Job();
        BeanUtil.copyProperties(oldJob, job);
        boolean result = this.updateById(job);
        if(!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "审核职位失败");
        }
        return true;
    }


    // 参数校验
    private void validate(HuntingTypeEnum huntingTypeEnum, EducationEnum educationEnum, ExperienceEnum experienceEnum, JobStateEnum jobStateEnum, CheckStatusEnum checkStatusEnum, Integer minSalary, Integer maxSalary, Date pubTime, Date endTime, Long companyId, Long positionTypeId) {
        // 参数校验
        ThrowUtils.throwIf(huntingTypeEnum == null, ErrorCode.PARAMS_ERROR, "招聘类型错误");
        ThrowUtils.throwIf(educationEnum == null, ErrorCode.PARAMS_ERROR, "学历要求错误");
        ThrowUtils.throwIf(experienceEnum == null, ErrorCode.PARAMS_ERROR, "工作经验错误");
        ThrowUtils.throwIf(jobStateEnum == null, ErrorCode.PARAMS_ERROR, "职位状态错误");
        ThrowUtils.throwIf(checkStatusEnum == null, ErrorCode.PARAMS_ERROR, "审核状态错误");
        ThrowUtils.throwIf(minSalary > maxSalary, ErrorCode.PARAMS_ERROR, "最低薪资不能大于最高薪资");
        ThrowUtils.throwIf(pubTime.after(endTime), ErrorCode.PARAMS_ERROR, "发布时间不能大于结束时间");

        long count1 = companyInfoService.lambdaQuery().eq(CompanyInfo::getId, companyId).count();
        ThrowUtils.throwIf(count1 == 0, ErrorCode.PARAMS_ERROR, "公司不存在");
        long count2 = positionTypeService.lambdaQuery().eq(PositionType::getId, positionTypeId).count();
        ThrowUtils.throwIf(count2 == 0, ErrorCode.PARAMS_ERROR, "职位类型不存在");
    }
}




